#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : lee

import sys
import os
import logging
import re
from SceneCheckTool.checkScript.CheckBase import CheckBase
from elsLibs.ProjectInfo import ProjectInfo

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import jarryLibs.mayakit.MayaUtils as mu
    reload(mu)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class CfxPgYetiImageAttrCheck(CheckBase):
    def __init__(self):
        super(CfxPgYetiImageAttrCheck, self).__init__()
        self.init_els()

    def init_els(self):
        self.els_project = ProjectInfo()

        # 通过文件名称获取资产信息
        maya_file = mu.sceneName()
        file_name = os.path.basename(maya_file)
        self.asset_short_type = file_name.split("_")[0]
        self.asset_name = file_name.split("_")[1]
        self.asset_type = self.els_project.asset_short_type_data[self.asset_short_type]


    def check_pgYeti_imagesource(self):
        """
        描述：pgYeti节点检查的启动函数
        """
        error_nodes = []
        for yeti_node in cmds.ls(type="pgYetiMaya"):
            # 判断节点是否存在Texture需求
            if not self.get_pgYeti_texture_nodes(yeti_node):
                continue
            # 检查image search path是否准确
            image_search_path = cmds.getAttr(yeti_node + ".imageSearchPath")
            if not image_search_path:
                error_nodes.append(yeti_node)
                continue
            if os.path.normpath(image_search_path) != os.path.normpath(self.imagesource_path):
                error_nodes.append(yeti_node)

        return error_nodes

    def get_pgYeti_texture_nodes(self, node):
        texture_nodes = []
        for graph_node in cmds.pgYetiGraph(node, listNodes=True):
            node_type = cmds.pgYetiGraph(node, node=graph_node, nodeType=True)
            if node_type == "texture":
                texture_nodes.append(graph_node)
        return texture_nodes

    @property
    def imagesource_path(self):
        imagesource_path = os.path.join(self.els_project.root_path, "Assets", self.asset_type, self.asset_name, "hair", "sourceimages")
        return os.path.normpath(imagesource_path)

    def check(self):
        result_proc = self.check_pgYeti_imagesource()
        if result_proc:
            result_log = u'Error:%s\n' % result_proc
        else:
            result_log = u'Succeed:没有问题\n'

        return result_log

    def fix(self):
        try:
            miss_nodes = self.check_pgYeti_imagesource()
            for node in miss_nodes:
                cmds.setAttr(node + ".imageSearchPath", self.imagesource_path, type="string")
            return u'Succeed:没有问题\n'
        except:
            self.check()

